package service

import (
	"github.com/cihub/seelog"
	"shop/config"
	"shop/dao"
	"shop/utils/result"
	"shop/utils/wxpay"
)

// OrderPay 订单支付：微信小程序支付
func OrderPay(shopId int, userId int64, orderNo, payType string) *result.Result {
	order := dao.GetOrderByOrderNoAndUserId(orderNo, userId)
	if order == nil || order.OrderNo == "" {
		return result.Fail("order not exists")
	}

	shop := GetShopById(shopId)
	if shop == nil || shop.Id == 0 {
		return result.Fail("商家不存在或已下线")
	}

	params := &wxpay.UnifiedOrderParams{
		OutTradeNo: orderNo,
		TotalFee:   order.TotalPrice,
		Body:       shop.Name + "-" + orderNo,
		TradeType:  payType,
		Openid:     GetUserInfo(userId).Username,
		NotifyUrl:  config.WeixinPayNotify,
	}
	cli := wxpay.NewClient(shop.WxMpAppId, shop.WxPayMchId, shop.WxPayApiKey)
	payData, err := cli.UnifiedOrder(params)
	if err != nil {
		seelog.Errorf("微信下单失败，err: %+v", err)
		return result.Fail(err.Error())
	}
	return result.Ok(payData)
}
